package com.yuexun.dhdoctor.module.departmentDocumentNew.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.departmentDocumentNew.Act_Doc_Common_New;
import com.yuexun.dhdoctor.module.departmentDocumentNew.adapter.FileAdapter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.adapter.FilesAdapter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.DocDepartBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.ShareDocBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.ShareDocModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.UserDepartDocTreeModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.AddDownloadNumPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.ShareDocPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.UserDepartDocTreePresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IAddDownloadNumView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IShareDocView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IUserDepartDocTreeView;
import com.yuexun.dhdoctor.util.FileUtils;
import com.yuexun.dhdoctor.util.ListChangeUtil;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;
import com.yuexun.dhdoctor.widget.HttpDownloader;
import com.yuexun.dhdoctor.widget.LoadingDialog;


import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/11/28 0028.
 */

public class Frag_Doc_Common_New extends KJFragment implements IUserDepartDocTreeView, IShareDocView {
    @Bind(R.id.et_doc_department)
    EditText etDocDepartment;
    @Bind(R.id.file_list)
    FixedSwipeListView fileList;
    @Bind(R.id.files_list)
    FixedSwipeListView filesList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.tv_download)
    TextView tvDownload;

    private LoadingDialog loadingDialog;

    private UserDepartDocTreePresenter docDepartPresenter;
    private ShareDocPresenter shareDocPresenter;
    private AddDownloadNumPresenter addNumPresenter;

    //当前目录
    private List<DocDepartBean> docDepartBeans = new ArrayList<>();

    FilesAdapter adapter;

    private List<ShareDocBean> docDatas = new ArrayList<>();

    private List<ShareDocBean> downDoc = new ArrayList<>();

    FileAdapter fileAdapter;

    private int downPosition = 0;


    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.frag_doc_department_new, null);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        tvDownload .setVisibility(View.VISIBLE);
        loadingDialog = new LoadingDialog(getActivity());
        docDepartPresenter = new UserDepartDocTreePresenter(this, new UserDepartDocTreeModel());
        shareDocPresenter = new ShareDocPresenter(this, new ShareDocModel());
        ApiGetFile();

        fileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), Act_Doc_Common_New.class);
                Bundle bundle = new Bundle();
                bundle.putString("info", docDepartBeans.get(position).getChildList());
                bundle.putString("docId", docDepartBeans.get(position).getDepartDocId());
                bundle.putString("type", docDepartBeans.get(position).getDocType() + "");
                bundle.putString("name", docDepartBeans.get(position).getDepartDocName() + "");
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        filesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String[] filenames = docDatas.get(position).getDocName().split("\\.");
                if (FileUtils.isFileExist(AppConfig.FILE_CONTENT + docDatas.get(position).getFileUUId() + "." + filenames[filenames.length - 1])) {
                    FileUtils fileUtils = new FileUtils(getActivity());
                    Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT
                            + docDatas.get(position).getFileUUId() + "." + filenames[filenames.length - 1]);
                    try {
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ViewInject.toast("当前文件未下载");
                }
            }
        });
    }

    private void ApiGetFile() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        docDepartPresenter.getDepartTree(params);
    }

    //设置文档列表请求
    private void ApiGetDocDatas(String docId,String type) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("departDocId", docId);
        params.put("docType", type);
        params.put("pageIndex", 1 + "");
        params.put("pageSize", 999999 + "");
//            params.put("inquireKey", key);
        shareDocPresenter.getShareDocDatas(params);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_doc_department_search,R.id.tv_download})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_doc_department_search:
                break;
            case R.id.tv_download:
                setDown();
                break;
        }
    }

    @Override
    public void showShareDocDatas(BaseEntity<ShareDocBean> getShareDocDatas) {
        if ("200".equals(getShareDocDatas.getStatus())) {
            docDatas.clear();
            docDatas = getShareDocDatas.getDatas();
            fileAdapter = new FileAdapter(filesList, docDatas, R.layout.item_files,getActivity());
            filesList.setAdapter(fileAdapter);
        } else {
            ViewInject.toast(getShareDocDatas.getMessage());
        }
        if(emptyLayout.isLoading())
        {
            emptyLayout.dismiss();
        }
    }

    @Override
    public void showDepartTree(BaseEntity<DocDepartBean> getDepartTree) {
        if ("200".equals(getDepartTree.getStatus())) {
            ArrayList<DocDepartBean> departDatas;
            departDatas = getDepartTree.getDatas();
            DocDepartBean docDepartBean = new DocDepartBean();
            for (DocDepartBean item : departDatas) {
                if (item.getDepartDocId().equals("a_0")) {
                    docDepartBean = item;
                }
            }
            docDepartBeans = JSON.parseArray(docDepartBean.getChildList(), DocDepartBean.class);
            if (docDepartBeans.size() > 0) {
                adapter = new FilesAdapter(fileList, docDepartBeans, R.layout.item_file);
                fileList.setAdapter(adapter);
                emptyLayout.dismiss();
            }

            ApiGetDocDatas(docDepartBean.getDepartDocId(),docDepartBean.getDocType()+"");

        } else {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }
    }

    //设置下载
    public void setDown() {
        downDoc.clear();
        downPosition = 0;
        for (ShareDocBean beanDate : docDatas) {
            if (beanDate.isSelect()) {
                downDoc.add(beanDate);
            }
        }
        if (downDoc.size() > 0) {
            loadingDialog.show();
            downloadFile(downDoc.get(downPosition));
        } else {
            ViewInject.toast("请选择要下载的文件");
        }
    }

    private void downloadFile(final ShareDocBean selectDoc) {
        final String[] filenames = selectDoc.getDocName().split("\\.");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpDownloader httpDownLoader = new HttpDownloader(getActivity());
                Log.e("---------", AppConfig.WEB_FILE + selectDoc.getFileUUId());
                handler.sendEmptyMessage(0);
                int result = httpDownLoader.downfile(AppConfig.WEB_FILE + selectDoc.getFileUUId(), AppConfig.FILE_CONTENT,
                        selectDoc.getFileUUId() + "." + filenames[filenames.length - 1]);
                if (result == 0 || result == 1) {   //下载成功或已经存在
                    downPosition = downPosition + 1;
                    if (downPosition < downDoc.size()) {
                        downloadFile(downDoc.get(downPosition));
                    } else {
                        addDownloadNum();
                        handler.sendEmptyMessage(1);
                    }
                } else if (result == -1) {         //下载失败
                    handler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
//                    ViewInject.toast("开始下载...");
                    break;
                case 1:
                    ViewInject.toast("下载完成");
                    loadingDialog.dismiss();
                    break;
                case 2:
                    ViewInject.toast("下载失败");
                    loadingDialog.dismiss();
                    break;
            }
        }
    };

    private void addDownloadNum() {
        addNumPresenter = new AddDownloadNumPresenter(new ShareDocModel(), new IAddDownloadNumView() {
            @Override
            public void addDocDownloadNum(BaseEntity<String> bean) {
                fileAdapter.notifyDataSetChanged();
            }
        });

        List<String> fileUuid = new ArrayList<>();
        List<String> docId = new ArrayList<>();
        String strFileUuid;
        String strDocId;

        for (ShareDocBean item : downDoc) {
            fileUuid.add(item.getFileUUId());
            docId.add(item.getDocId() + "");
        }
        strFileUuid = ListChangeUtil.listToString(fileUuid, ";");
        strDocId = ListChangeUtil.listToString(docId, ";");

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("fileUUId", strFileUuid);
        params.put("docId", strDocId);
        addNumPresenter.addDocDownloadNum(params);
    }
}
